/* @flow */
'use strict';

var React = require('react-native');
var News_DetailView = require('./News_DetailView');
var {
  StyleSheet,
  View,
  ListView,
  Text,
  ActivityIndicatorIOS,
} = React;

var API_PATH = "http://apis.baidu.com/txapi/keji/keji?num=100";
var API_KEY = "694fe0426437ca7b94f17a3148046ad7";

var ContentCell = require('./ContentCell');

var Component = React.createClass({

  render: function() {
  	if (!this.state.loadingStatus) {
  		return (
	  		<ActivityIndicatorIOS
          		style={[styles.activityIndicatorIOSStyle, {height: 40}]}
          		color="#0000ff"/>);
  	}else{
  		return (
      		<ListView
      		  style={styles.listViewStyle}
      		  dataSource={this.state.dataSource}
      		  renderRow={this.getRenderView} />
      		
   		 );
  	}
  },

  getInitialState: function() {
  var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    return {
      dataSource: ds.cloneWithRows(['row 1', 'row 2']),
      loadingStatus: false,
    };
  },

  componentWillMount: function() {
  	this.getDataFromServer();
  },

  getRenderView:function(newsItem){
  	return (<ContentCell newsItem = {newsItem}
  					     onPressThisCell = {()=>this.cellPress(newsItem)}
  							/>);
  },

//点击cell发生页面跳转
  cellPress:function(newsItem){
  	console.log('newsItem is ===>'+newsItem);
  	this.props.navigator.push({
  		component:News_DetailView,
  		title:'新闻详细',
  		passProps:{newsItem:newsItem},
  	});

  },

  getDataFromServer: function () {
  	fetch(API_PATH,{
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'apikey':API_KEY
      }
    })
    .then((response) => response.json())
    .then((responseData) => {
      this.dataFilter(responseData);
      console.log(responseData);
      this.setState({
        dataSource:this.state.dataSource.cloneWithRows(responseData),
        loadingStatus:true,
      });
    })
    .catch((error) => {
      console.warn(error);
    });
  },

  dataFilter:function(responseData){
  	delete(responseData["code"]);
  	delete(responseData["msg"]);
  }

});


var styles = StyleSheet.create({


	loadingStyle:{
		flex:1,
		justifyContent:'center',
	},

	listViewStyle:{
		flex:1,
		marginTop:64
	},
	activityIndicatorIOSStyle:{
		marginTop:100,
		alignItems: 'center', 
		justifyContent: 'center'
	},

});


module.exports = Component;
